package controllers

import (
	"errors"
	"news/common/response"
	"news/constStatus"
	"news/dao/mysql"
	"news/logic"
	"news/models"
	"strconv"

	"github.com/go-playground/validator/v10"

	"go.uber.org/zap"

	"github.com/gin-gonic/gin"
)

// 社区 添加分类名称
func AddCommunityHandler(c *gin.Context) {
	p := new(models.Community)
	if err := c.ShouldBindJSON(p); err != nil {
		zap.L().Error("add with invalid param", zap.Error(err))
		errors, ok := err.(validator.ValidationErrors)
		if !ok {
			response.FailWithMessage(err.Error(), c)
			return
		}
		response.FailWithMessage(removeTopStruct(errors.Translate(trans)), c)
		return
	}
	if err := logic.Community(p); err != nil {
		zap.L().Error("add data failed", zap.Error(err))
		if errors.Is(err, mysql.ErrorCommunityNameExist) {
			response.FailWithMessage("社区分类名称已经存在", c)
			return
		}
		response.FailWithMessage("参数错误", c)
		return
	}
	response.OkWithMessage("社区分类保存成功", nil, c)
}

// 社区分类编辑 返回信息
func EditCommunityCategory(c *gin.Context) {
	paramId := c.Param("id")
	CommunityID, err := strconv.ParseInt(paramId, 10, 64)
	if err != nil {
		response.FailWithMessage("参数错误", c)
	}
	communityEditList, err := logic.CommunityEdit(CommunityID)
	if err != nil {
		zap.L().Error("mysql.GetCommunityEditList() failed", zap.Error(err))
		response.FailWithMessage("服务繁忙", c)
		return
	}
	response.OkWithMessage("success", communityEditList, c)
}

// 社区列表

func CommunityList(c *gin.Context) {
	list, err := logic.GetCommunityList()
	if err != nil {
		zap.L().Error("mysql.CommunityList() failed", zap.Error(err))
		response.FailWithMessage(constStatus.CodeServerBuy, c)
		return
	}
	response.OkWithMessage("success", list, c)
}

//社区列表详情id
func CommunityDetailId(c *gin.Context) {
	paramId := c.Param("id")
	id, err := strconv.ParseInt(paramId, 10, 64)
	if err != nil {
		response.FailWithMessage(constStatus.CodeParamError, c)
		return
	}
	detail, err := logic.GetCommunityDetail(id)
	if err != nil {
		response.FailWithMessage(constStatus.CodeServerBuy, c)
		return
	}
	response.OkWithMessage("success", detail, c)
}
